package cn.edu.nju.software.action.transaction;

import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import cn.edu.nju.software.bean.show.BookItemInOrder;
import cn.edu.nju.software.bean.show.BookShow;
import cn.edu.nju.software.bean.storage.Book;
import cn.edu.nju.software.service.intf.BookService;
import cn.edu.nju.software.util.Constants;
import cn.edu.nju.software.util.SessionOperator;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class AddToCartAction extends ActionSupport implements SessionAware {

	private int id;
	private int quantity;
	private BookService bookService;
	private Map<String, Object> session;

	public void setId(int id) {
		this.id = id;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public void setBookService(BookService bookService) {
		this.bookService = bookService;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	
	@Override
	public String execute() throws Exception {
		BookShow bookShow;
		Book book;
		@SuppressWarnings("unchecked")
		List<BookItemInOrder> cart = (List<BookItemInOrder>) session.get(Constants.SESSION_CART);
		for (BookItemInOrder item : cart) {
			if (item.getBook().getBookID() == id) {
				item.setQuantity(item.getQuantity() + quantity);
				return SUCCESS;
			}
		}
		if ((bookShow = SessionOperator.searchBookInSession(session, id)) == null) {
			book = bookService.getBookById(id);
		} else {
			book = bookShow.getBook();
		}
		cart.add(new BookItemInOrder(book, quantity, book.getPrice()));
		return SUCCESS;
	}

	public void add() throws Exception {
		BookShow bookShow;
		Book book;
		@SuppressWarnings("unchecked")
		List<BookItemInOrder> cart = (List<BookItemInOrder>) session.get(Constants.SESSION_CART);
		for (BookItemInOrder item : cart) {
			if (item.getBook().getBookID() == id) {
				item.setQuantity(item.getQuantity() + quantity);
				return;
			}
		}
		if ((bookShow = SessionOperator.searchBookInSession(session, id)) == null) {
			book = bookService.getBookById(id);
		} else {
			book = bookShow.getBook();
		}
		cart.add(new BookItemInOrder(book, quantity, book.getPrice()));
	}
	
}
